<template>
  <div>
    <el-tabs type="border-card">
      <el-tab-pane label="个人中心">
        <el-form>
          <el-form-item label="头像">
            <img :src="user.icon_url" style="width:100px">
          </el-form-item>
          <el-form-item label="账号">
            <span>{{ user.username }}</span>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="dialogVisible = true">修改个人资料</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <el-dialog title="提示" :visible.sync="dialogVisible" width="40%">
      <el-form>
        <el-form-item>
          <el-upload class="avatar-uploader" action="/api/private/v1/upload" :show-file-list="false"
            :on-success="handleAvatarSuccess" drag :header="user.token">
            <template v-if="!icon_url">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
            </template>
            <template v-else>
              <img :src="icon_url" style="height:100%" class="avatar">
            </template>

          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  computed: {
    ...mapGetters(['user'])
  },
  data () {
    return {
      icon_url: '',
      dialogVisible: false,
      loading: false
    }
  },
  methods: {
    handleAvatarSuccess (res, file) {
      // console.log(res)
      this.$message.success('上传成功')
      this.icon_url = res.data.path
    },
    async submit () {
      console.log(this.user)
      this.loading = true
      const { data: res } = await this.$http.post('/user/updateIcon', { icon_url: this.icon_url })
      if (res.code === 0) {
        this.$message.success('更改成功')
        const params = { ...this.user, icon_url: this.icon_url }
        this.$store.dispatch('user/setUser', params)
      }
      this.loading = false
      this.dialogVisible = false
    }
  }
}
</script>

<style>
</style>
